package com.fire8.dolphin.ui.imgcache;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.lang.ref.SoftReference;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import com.fire8.dolphin.ui.DolphinApplication;
import com.fire8.dolphin.utils.LogUtil;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;

/**
 * Title: HuiXiHuan<br>
 * Description:The new privilege<br>
 * Create DateTime: 2012-01-05,09:20 AM <br>
 * SVN last modify person: $KouPei $ <br>
 * SVN last modify DateTime: $Date: 2012-01-12,10:20 AM $<br>
 * SVN last version: $Revision: 1.0 $ <br>
 * 
 * @author ZhaoLin
 */
public class AsyncImageLoader
{
    private BitmapFactory.Options opts = new BitmapFactory.Options();
    
    private LinkedHashMap<String, SoftReference<Bitmap>> imageCache = new LinkedHashMap<String, SoftReference<Bitmap>>();
    
    public Bitmap loadDrawable(final String imageUrl,
            final ImageCallback callback)
    {
//        if(imageCache.size()>7)
//        {
//            Iterator<String> iterator = imageCache.keySet().iterator();
//            if(iterator.hasNext())
//            {
//                try
//                {
//                    SoftReference<Bitmap> softReference = imageCache.get(iterator.next());
//                    softReference.get().recycle();
//                    softReference.clear();
//                    imageCache.remove(iterator.next());
//                }
//                catch (Exception e)
//                {
//                    LogUtil.e("",e);
//                }
//                
//            }
//        }
        opts.inSampleSize = 1;
        if (imageCache.containsKey(imageUrl))
        {
            SoftReference<Bitmap> softReference = imageCache.get(imageUrl);
//            LogUtil.d("softReference--------->" + softReference.get());
            if (softReference.get() != null)
            {
                LogUtil.d("从缓存里取的"+imageUrl);
                return softReference.get();
            }
        }
        try
        {
            File file = new File(DolphinApplication.IMG_PATH + imageUrl.hashCode()+"");
            if (file.exists())
            {
                LogUtil.d("从存储卡里取的"+imageUrl);
                Bitmap bmp = BitmapFactory.decodeFile(DolphinApplication.IMG_PATH + imageUrl.hashCode()+"",
                        opts);
                imageCache.put(imageUrl, new SoftReference<Bitmap>(bmp));
                return bmp;
            }
        }
        catch (Exception e)
        {
            LogUtil.e("",e);
        }
        
        //LogUtil.d("存储卡里没有这张图片:"+DolphinApplication.IMG_PATH + imageUrl.hashCode()+".jpg");
        
        final Handler handler = new Handler()
        {
            @Override
            public void handleMessage(Message msg)
            {
                callback.setImageToImageView((Bitmap)msg.obj);
            }
        };
        new Thread()
        {
            public void run()
            {
                
                try
                {
                    Bitmap bmp = loadImageFromUrl(imageUrl);
                    if(bmp != null)
                    {
                        saveBitmapToSDCard(bmp,imageUrl.hashCode() + "");
                        imageCache.put(imageUrl, new SoftReference<Bitmap>(bmp));
                        Message msg = handler.obtainMessage(0, bmp);
                        handler.sendMessage(msg);
//                        LogUtil.d("发送handler消息");
                    }
                    
                }
                catch (Exception e)
                {
                    LogUtil.e("",e);
                }
                
            }
        }.start();
        return null;
        
    }
    
    protected Bitmap loadImageFromUrl(String imageUrl)
    {
        try
        {
            Bitmap bitmap = BitmapFactory.decodeStream(new URL(imageUrl).openStream(),
                    null,
                    opts);
            //LogUtil.d("取到图片了："+imageUrl);
            //LogUtil.d("图片hashcode："+bitmap.hashCode());
            return bitmap;
        }
        catch (Exception e)
        {
            //LogUtil.e("文件不存在", e);
            return null;
        }
    }
    
    public interface ImageCallback
    {
        public void setImageToImageView(Bitmap bmp);
    }
    
    private void saveBitmapToSDCard(Bitmap bitmap,String headName) throws Exception
    {
        //File headImage = new File(imagePath + headName);
        File dirFile = new File(DolphinApplication.IMG_PATH);  
        if(!dirFile.exists()){  
            dirFile.mkdir();  
        }
        File headImage = new File(DolphinApplication.IMG_PATH + headName);  
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(headImage));
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
        bos.flush();
        bos.close();
        //LogUtil.d("保存照片："+headName+".jpg");
    }
}
